﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Configuration;
using System.Data.SQLite;

namespace NewsSpider.App
{
    public partial class MainFrm : Form
    {
        delegate void SetTextCallback(string text);
        private Thread catchThread = null;

        NewsSpider.Utility.IniFile iniFile = new Utility.IniFile(Application.StartupPath + "\\config.ini");
        NewsSpider.Utility.IniFile iniFileVersion = new Utility.IniFile(Application.StartupPath + "\\version.ini");
        NewsSpider.Utility.IniFile iniFileData = new Utility.IniFile(Application.StartupPath + "\\data.ini");

        public MainFrm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 显示实时消息到showMsg
        /// </summary>
        /// <param name="strMessage">实时消息</param>
        private void SetText(string strMessage)
        {
            if (this.showMsg.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { strMessage });
            }
            else
            {
                this.showMsg.Text = strMessage;
            }
        }

        /// <summary>
        /// 关闭整个应用程序进程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void KillProcess(object sender, System.ComponentModel.CancelEventArgs e)
        {
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }

        private void MainFrm_Load(object sender, EventArgs e)
        {
            label5.ForeColor = Color.FromArgb(255, 0, 0);
            label6.ForeColor = Color.FromArgb(255, 0, 0);
            label15.ForeColor = Color.FromArgb(255, 0, 0);

            this.Closing += new CancelEventHandler(KillProcess);
            skinEngine1.SkinFile = NewsSpider.Utility.CommonHelper.GetCurrentSoftSkin();
            this.Icon = new Icon(NewsSpider.Utility.ICONHelper.SetFormICON());

            //软件标题
            this.Text = "云里新闻采集大师 " + iniFileVersion.GetString("cloudin_newsspider", "version", "");

            catchThread = new Thread(new ThreadStart(GetCatchWebsites));
            catchThread.Start();

            catchThread = new Thread(new ThreadStart(GetArticles));
            catchThread.Start();

            label5.ForeColor = Color.FromArgb(255, 0, 0);
            label6.ForeColor = Color.FromArgb(255, 0, 0);
            label15.ForeColor = Color.FromArgb(255, 0, 0);
            //wbFaq.Url = new Uri("http://bbs.cloudin.so/forum-51-1.html");

            //设置默认采集数据库源
            string strSQLite = "Data Source=" + System.Windows.Forms.Application.StartupPath + "\\data\\sqlite\\NewsSpider.db";
            iniFileData.WriteValue("Connection", "sqlite", strSQLite);
            NewsSpider.DBSqlHelp.ConnectionData.SaveConnectionSQLiteString(strSQLite);

            string strAccess = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Windows.Forms.Application.StartupPath + "\\data\\access\\NewsSpider.mdb";
            iniFileData.WriteValue("Connection", "access", strAccess);
            NewsSpider.DBSqlHelp.ConnectionData.SaveConnectionAccessString(strAccess);
        }

        private void GetCatchWebsites()
        {
            NewsSpider.DAL.CatchWebsitesSQLiteDAL cwsdal = new DAL.CatchWebsitesSQLiteDAL();
            cwsdal.BindCatchWebsitesDAL(dgvCatchWebsites, "select * from CatchWebsites where setup_status=2");
        }

        private void GetArticles()
        {
            NewsSpider.DAL.ArticlesSQLiteDAL asdal = new DAL.ArticlesSQLiteDAL();
            asdal.BindArticlesDAL(dgvArticles, "select * from Articles order by add_date desc");
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //设置默认采集数据库源
            string strSQLite = "Data Source=" + System.Windows.Forms.Application.StartupPath + "\\data\\sqlite\\NewsSpider.db";
            iniFileData.WriteValue("Connection", "sqlite", strSQLite);
            NewsSpider.DBSqlHelp.ConnectionData.SaveConnectionSQLiteString(strSQLite);

            string strAccess = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Windows.Forms.Application.StartupPath + "\\data\\access\\NewsSpider.mdb";
            iniFileData.WriteValue("Connection", "access", strAccess);
            NewsSpider.DBSqlHelp.ConnectionData.SaveConnectionAccessString(strAccess);

            btnStart.Enabled = false;
            btnStop.Enabled = true;
            //CatchWebsites();
            catchThread = new Thread(new ThreadStart(CatchWebsites));
            catchThread.Start();
        }

        /// <summary>
        /// 开始执行采集任务
        /// </summary>
        private void CatchWebsites()
        {

            int iTask = 1;
            try
            {
                //记录开始采集时间
                iniFile.WriteValue("AUTO", "STARTTIME", DateTime.Now.ToString());

                //获取抓取ID范围
                string strMinID = iniFile.GetString("AUTO", "CATCHID_MIN", "");
                string strMaxID = iniFile.GetString("AUTO", "CATCHID_MAX", "");

                NewsSpider.Utility.PublicValue.SaveMessage(Convert.ToDateTime(DateTime.Now).ToString("MM-dd HH:mm:ss") + " 开始采集网址任务...");
                this.SetText(NewsSpider.Utility.PublicValue.GetMessage());

                //读取抓取网址列表
                NewsSpider.BLL.CatchWebsitesSQLiteBLL cwsbll = new BLL.CatchWebsitesSQLiteBLL();
                List<NewsSpider.Model.CatchWebsites> list = new List<Model.CatchWebsites>();
                list = cwsbll.GetCatchWebsitesByWhereBLL("select * from CatchWebsites where is_catch=1 and site_id>=" + strMinID + " and site_id<=" + strMaxID + " order by site_id");//上传
                //list = clbll.GetCatchListByWhereBLL("select * from CatchList where is_catch=1 and catch_id>=200 and catch_id<=200 order by catch_id");//测试
                int iTaskCount = list.Count;
                foreach (NewsSpider.Model.CatchWebsites cws in list)
                {

                    string strSiteID = cws.SiteId.ToString();
                    string strSiteName = cws.SiteName;
                    string strSiteURL = cws.SiteUrl;
                    string strWebCharset = "gb2312";

                    iniFile.WriteValue("CATCH", "SiteName", strSiteName);
                    iniFile.WriteValue("CATCH", "ListPageUrl", strSiteURL);
                    iniFile.WriteValue("CATCH", "Charset", strWebCharset);

                    string strListTagStart = cws.TagStartList;
                    string strListTagEnd = cws.TagEndList;
                    iniFile.WriteValue("CATCH", "ListStartTag", strListTagStart);
                    iniFile.WriteValue("CATCH", "ListEndTag", strListTagEnd);

                    string strLinkTagStart = cws.TagLinkStart;
                    string strLinkTagEnd = cws.TagLinkEnd;
                    iniFile.WriteValue("CATCH", "LinkStartTag", strLinkTagStart);
                    iniFile.WriteValue("CATCH", "LinkEndTag", strLinkTagEnd);

                    string strTitleTagStart = cws.TagStartTitle;
                    string strTitleTagEnd = cws.TagEndTitle;
                    iniFile.WriteValue("CATCH", "TitleStartTag", strTitleTagStart);
                    iniFile.WriteValue("CATCH", "TitleEndTag", strTitleTagEnd);

                    string strContentTagStart = cws.TagStartContent;
                    string strContentTagEnd = cws.TagEndContent;
                    iniFile.WriteValue("CATCH", "ContentStartTag", strContentTagStart);
                    iniFile.WriteValue("CATCH", "ContentEndTag", strContentTagEnd);

                    string strAuthorTagStart = cws.TagStartAuthor;
                    string strAuthorTagEnd = cws.TagEndAuthor;
                    iniFile.WriteValue("CATCH", "AuthorStartTag", strAuthorTagStart);
                    iniFile.WriteValue("CATCH", "AuthorEndTag", strAuthorTagEnd);

                    string strSourceTagStart = cws.TagStartSource;
                    string strSourceTagEnd = cws.TagEndSource;
                    iniFile.WriteValue("CATCH", "SourceStartTag", strSourceTagStart);
                    iniFile.WriteValue("CATCH", "SourceEndTag", strSourceTagEnd);

                    NewsSpider.Utility.PublicValue.SaveMessage(Convert.ToDateTime(DateTime.Now).ToString("MM-dd HH:mm:ss") + " 开始采集 -> " + strSiteName +",共【" + iTaskCount + "】个任务，当前正在执行第【" + iTask + "】个任务");
                    this.SetText(NewsSpider.Utility.PublicValue.GetMessage());

                    NewsSpider.BLL.WebSites.GetListPageHtml(showMsg);

                    NewsSpider.Utility.PublicValue.SaveMessage("\r\n" + Convert.ToDateTime(DateTime.Now).ToString("MM-dd HH:mm:ss") + " " + strSiteName + " 抓取结束,共【" + iTaskCount + "】个任务，当前第【" + iTask + "】个任务已执行完毕！");
                    this.SetText(NewsSpider.Utility.PublicValue.GetMessage());

                    iTask++;
                }

                NewsSpider.Utility.PublicValue.SaveMessage("\r\n" + Convert.ToDateTime(DateTime.Now).ToString("MM-dd HH:mm:ss") + " 抓取网址所有任务结束！");
                this.SetText(NewsSpider.Utility.PublicValue.GetMessage());

                //存储当前状态未已抓取完毕
                iniFile.WriteValue("AUTO", "STATUS", "1");
                //记录开始采集时间
                iniFile.WriteValue("AUTO", "ENDTIME", DateTime.Now.ToString());
                //清楚历史消息记录
                NewsSpider.Utility.PublicValue.m_strMessage = "";
            }
            catch (Exception ex)
            {
                NewsSpider.Utility.Log.SaveErrorLog("抓取任务 -> " + ex.Message);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = true;
            btnStop.Enabled = false;
            catchThread.Abort();
        }

        private void btnRefreshWebsite_Click(object sender, EventArgs e)
        {
            catchThread = new Thread(new ThreadStart(GetCatchWebsites));
            catchThread.Start();
        }

        private void btnAddWebsite_Click(object sender, EventArgs e)
        {
            AddWebsiteFrm openWin = new AddWebsiteFrm();
            openWin.Show();
        }

        private void btnDelWebsite_Click(object sender, EventArgs e)
        {
            try
            {
                NewsSpider.BLL.CatchWebsitesSQLiteBLL cwsbll = new BLL.CatchWebsitesSQLiteBLL();
                cwsbll.DeleteCatchWebsitesBLL("delete from CatchWebsites");

                //刷新
                catchThread = new Thread(new ThreadStart(GetCatchWebsites));
                catchThread.Start();
            }
            catch (Exception ex)
            {
                NewsSpider.Utility.Log.SaveErrorLog("删除全部采集网址 ->" + ex.Message);
            }
        }

        private void btnRefreshNews_Click(object sender, EventArgs e)
        {
            catchThread = new Thread(new ThreadStart(GetArticles));
            catchThread.Start();
        }

        private void btnDelNews_Click(object sender, EventArgs e)
        {
            try
            {
                NewsSpider.BLL.ArticlesSQLiteBLL asbll = new BLL.ArticlesSQLiteBLL();
                asbll.DeleteArticlesBLL("delete from Articles");

                catchThread = new Thread(new ThreadStart(GetArticles));
                catchThread.Start();
            }
            catch (Exception ex)
            {
                NewsSpider.Utility.Log.SaveErrorLog("删除全部文章 ->" + ex.Message);
            }
        }

        private void dgvArticles_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1 && e.RowIndex != -1)
            {
                //修改文章
                string strGetArticleID = dgvArticles.Rows[e.RowIndex].Cells[0].FormattedValue.ToString();
                ViewArticleFrm openWin = new ViewArticleFrm(strGetArticleID);
                openWin.Show();
            }
            if (e.ColumnIndex == 4 && e.RowIndex != -1)
            {
                //打开文章采集来源网址
                string strUrl = dgvArticles.Rows[e.RowIndex].Cells[6].FormattedValue.ToString();
                System.Diagnostics.Process.Start(strUrl);
            }
            
        }

        private void dgvCatchWebsites_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2 && e.RowIndex != -1)
            {
                //打开文章采集来源网站
                string strUrl = dgvCatchWebsites.Rows[e.RowIndex].Cells[2].FormattedValue.ToString();
                System.Diagnostics.Process.Start(strUrl);
            }
        }

        private void btnFeedback_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFeedbackTitle.Text.Trim()))
            {
                MessageBox.Show("电子邮件不能为空！");
                txtFeedbackTitle.Focus();
            }
            else if (!NewsSpider.Utility.CommonHelper.CheckIsEmail(txtFeedbackTitle.Text.Trim()))
            {
                MessageBox.Show("电子邮件格式不正确！");
                txtFeedbackTitle.Focus();
            }
            else if (string.IsNullOrEmpty(txtFeedbackContent.Text.Trim()))
            {
                MessageBox.Show("反馈内容不能为空！");
                txtFeedbackContent.Focus();
            }
            else
            {
                btnFeedback.Enabled = false;
                btnFeedback.Text = "     正在提交";
                catchThread = new Thread(new ThreadStart(SendFeedback));
                catchThread.Start();
            }
        }

        private void SendFeedback()
        {
            NewsSpider.Utility.WebClient wc = new NewsSpider.Utility.WebClient();
            wc.Encoding = System.Text.Encoding.GetEncoding("gb2312");
            wc.OpenRead("http://www.cloudin.so/customers/api/feedback.aspx?c=0&email=" + txtFeedbackTitle.Text.Trim() + "&content=" + txtFeedbackContent.Text.Trim());
            string strGetHtmlCode = wc.RespHtml;

            MessageBox.Show("感谢您的建议，祝您工作愉快！");
            btnFeedback.Enabled = true;
            btnFeedback.Text = "     确认提交";
            txtFeedbackContent.Text = "";
            txtFeedbackTitle.Text = "";
        }

        private void btnMainSet_Click(object sender, EventArgs e)
        {
            SetFrm openWin = new SetFrm();
            openWin.Show();
        }

        private void imageApps1_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("1");
            openWin.Show();
        }

        private void btnApps1_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("1");
            openWin.Show();
        }

        private void imageApps2_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("2");
            openWin.Show();
        }

        private void btnApps2_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("2");
            openWin.Show();
        }

        private void imageApps3_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("3");
            openWin.Show();
        }

        private void btnApps3_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("3");
            openWin.Show();
        }

        private void imageApps4_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("4");
            openWin.Show();
        }

        private void btnApps4_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("4");
            openWin.Show();
        }

        private void imageApps5_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("5");
            openWin.Show();
        }

        private void btnApps5_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("5");
            openWin.Show();
        }

        private void imageApps6_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("6");
            openWin.Show();
        }

        private void btnApps6_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("6");
            openWin.Show();
        }

        private void imageApps7_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("7");
            openWin.Show();
        }

        private void btnApps7_Click(object sender, EventArgs e)
        {
            AppsViewFrm openWin = new AppsViewFrm("7");
            openWin.Show();
        }

        private void imageApps8_Click(object sender, EventArgs e)
        {
            MessageBox.Show("敬请期待，即将上线！");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://bbs.cloudin.so/forum-51-1.html");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MoneyFrm openWin = new MoneyFrm();
            openWin.Show();
        }

        private void timerUpdate_Tick(object sender, EventArgs e)
        {
            CheckSoftVersion();
        }

        /// <summary>
        /// 检查软件是否有更新
        /// </summary>
        private void CheckSoftVersion()
        {
            try
            {
                string strNewVersion = NewsSpider.Utility.SoftUpdate.GetNewVersion();
                string strLocationVersion = iniFileVersion.GetString("cloudin_newsspider", "version", "");

                if (string.IsNullOrEmpty(strNewVersion))
                {
                    strLocationVersion = strNewVersion;
                }

                if (strNewVersion != strLocationVersion)
                {
                    timerUpdate.Enabled = false;

                    if (MessageBox.Show("检测到新版本，您是否需要更新？", "提醒", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        this.Hide();
                        UpdateFrm openWin = new UpdateFrm();
                        openWin.Show();
                    }
                }
                else
                {
                    string strGetVersion = iniFileVersion.GetString("cloudin_newsspider", "version", "");
                    this.Text = "云里新闻采集大师 " + strGetVersion + "(已是最新版)";
                }
            }
            catch (Exception ex)
            {
                NewsSpider.Utility.Log.SaveErrorLog("检查软件是否有更新 -> " + ex.Message);
            }

        }


    }
}
